package com.example.demo.netty;

import com.example.demo.demoApi.NettyExecutor;
import com.example.demo.demoApi.msg.AbstractMsg;
import com.example.demo.utils.JSONUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * netty handler
 * 封装了发送消息的方法
 */
@Slf4j
public abstract class AbstractServerHandler extends ChannelInitializer<SocketChannel> {
    protected static final int BUFFER_SIZE = 64 * 1024;
    protected static final String DELIMITER = "\r\n";

    protected NettyExecutor apiExecutor;

    /**
     * 给Socket通道发送消息
     */
    public void sendSocketMsg(ChannelHandlerContext ctx, AbstractMsg msg) {
        if (ctx != null && msg != null) {
            String message = JSONUtil.objToJson(msg);
            ctx.writeAndFlush(message);
            log.debug("resp-msg:{}, ctx:{}", message, ctx);
        } else {
            log.warn("ctx and msg must not be null! ctx:{}, msg:{}", ctx, msg);
        }
    }
}
